package com.example.demo.conf;

import com.google.common.collect.Maps;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.DefaultIdStrategy;
import io.protostuff.runtime.IdStrategy;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;

/**
 * ProtoStuff序列化工具类
 * 相比于json速度更快，占用cpu更小，建议使用
 * date:  2016/4/23 12:46
 *
 * @author funcas
 * @version 1.0
 */
public class ProtoStuffSerializerUtil {

    static final DefaultIdStrategy STRATEGY = new DefaultIdStrategy(IdStrategy.DEFAULT_FLAGS
            | IdStrategy.MORPH_COLLECTION_INTERFACES
            | IdStrategy.MORPH_MAP_INTERFACES
            | IdStrategy.MORPH_NON_FINAL_POJOS);
    private static Map<Class<?>, Schema<?>> cachedSchema = Maps.newConcurrentMap();

    private static Objenesis objenesis = new ObjenesisStd(true);

    private ProtoStuffSerializerUtil() {
    }

    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> targetClass) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(targetClass);
        if (schema == null) {
            schema = RuntimeSchema.getSchema(targetClass, STRATEGY);
            cachedSchema.put(targetClass, schema);
        }
        return schema;
    }

    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    public static <T> T deserialize(byte[] data, Class<T> targetClass) {
        try {
            Schema<T> schema = getSchema(targetClass);
            T message = (T) objenesis.newInstance(targetClass);

            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
